import { defineStore } from 'pinia'
import { login, logout } from '@/api/auth'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}')
  }),

  getters: {
    isLogin: (state) => !!state.token,
    username: (state) => state.userInfo.username || '',
    realName: (state) => state.userInfo.realName || '',
    role: (state) => state.userInfo.role || '',
    isAdmin: (state) => state.userInfo.role === 'ADMIN',
    isEmployee: (state) => state.userInfo.role === 'EMPLOYEE'
  },

  actions: {
    // 登录
    async login(loginForm) {
      try {
        console.log('发送登录请求:', loginForm)
        const res = await login(loginForm)
        console.log('登录响应:', res)
        
        const data = res.data
        console.log('登录数据:', data)
        
        this.token = data.token
        this.userInfo = {
          userId: data.userId,
          username: data.username,
          realName: data.realName,
          role: data.role,
          employeeNo: data.employeeNo,
          department: data.department,
          team: data.team
        }
        
        // 保存到本地存储
        localStorage.setItem('token', this.token)
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        
        console.log('登录成功，用户信息:', this.userInfo)
        return true
      } catch (error) {
        console.error('登录失败详情:', error)
        console.error('错误响应:', error.response)
        return false
      }
    },

    // 退出登录
    async logout() {
      try {
        if (this.token) {
          await logout()
        }
      } catch (error) {
        console.error('退出登录失败:', error)
      } finally {
        this.clearUserInfo()
        router.push('/login')
      }
    },

    // 清除用户信息
    clearUserInfo() {
      this.token = ''
      this.userInfo = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  }
})